
NAVI_TMPL = """		<navPoint id="{ID}" playOrder="{PLAY_ORDER}">
			<navLabel>
				<text>
					{TEXT}
				</text>
			</navLabel>
			<content src="{HREF}" />{SUBNAV}
		</navPoint>"""

SUBNAV_TMPL = '\n' + '\n'.join(['\t' + x for x in NAVI_TMPL.split('\n')]).replace('{SUBNAV}', '')

NCX_TMPL = """<?xml version="1.0"?>
<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN"
 "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
 <head>
 </head>
        <docTitle>
               <text>Book title</text>
        </docTitle>
	<navMap>
{CONTEXT}
	</navMap>
</ncx>
"""

po = 0
def BuildNCX(data):
    global po
    po = 0
    def PlayOrder():
        global po
        po += 1
        return po
    return NCX_TMPL.format(CONTEXT='\n'.join([NAVI_TMPL.format(ID="ch" + f.id, PLAY_ORDER=PlayOrder(), TEXT=f.text, HREF=f.href, SUBNAV = \
            '' + ''.join([SUBNAV_TMPL.format(ID="ch" + f.id + "_" + sf.id, PLAY_ORDER=PlayOrder(), TEXT=sf.text, HREF=sf.anchor) for ix, sf in enumerate(f.sf)]) \
            ) for f in data]))

def BuildTOC(data):
    TOC_TMPL = """<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TOC</title>
<!-- <link type="text/css" href="kf8.css" media="amzn-kf8" rel="Stylesheet"/> -->
<!-- <link type="text/css" href="mobi.css" media="amzn-mobi" rel="Stylesheet"/> -->
<!-- <link type="text/css" href="styles.css" rel="Stylesheet"/> -->
</head>
<body>

<h1 id="toc">Table of Contents</h1>

<ul>
{ITEMS}</ul>
</body>
</html>
"""
    UL_TMPL = """    <ul>
{ITEMS}    </ul>
"""
    LVL1_TMPL = """    <li><a href="{HREF}">{TEXT}</a>
{UL}    </li>
"""
    LVL2_TMPL = """        <li><a href="{HREF}">{TEXT}</a></li>
"""
    return TOC_TMPL.format(ITEMS=''.join([LVL1_TMPL.format(HREF=f.href, TEXT=f.text, UL= \
            UL_TMPL.format(ITEMS=''.join([LVL2_TMPL.format(HREF=sf.anchor, TEXT=sf.text) for sf in f.sf])) if f.sf else '' \
            ) for f in data]))
